<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>除去图像背景</title>
		<style>
			/* 全局样式 */
			body {
				margin: 0;
				padding: 0;
				background: linear-gradient(45deg, #ff6ec7, #4f9e8e); /* 渐变背景 */
				font-family: "Roboto", sans-serif;
				display: flex;
				justify-content: center;
				align-items: center;
				height: 100vh;
				color: #fff;
				overflow: hidden;
			}

			/* 中心容器 */
			.container {
				background: rgba(0, 0, 0, 0.7); /* 半透明背景 */
				padding: 40px 30px;
				border-radius: 12px;
				box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
				text-align: center;
				max-width: 800px;
				width: 100%;
			}

			/* 标题 */
			h1 {
				font-size: 32px;
				margin-bottom: 30px;
			}

			/* 动态光效 */
			@keyframes textGlow {
				0% {
					text-shadow: 0 0 5px #ff6ec7, 0 0 10px #ff6ec7, 0 0 15px #ff6ec7;
				}
				100% {
					text-shadow: 0 0 10px #f79c42, 0 0 20px #f79c42, 0 0 30px #f79c42;
				}
			}

			/* 上传表单 */
			.upload-form {
				margin-bottom: 30px;
			}

			/* 添加拖拽区域样式 */
			.drop-zone {
				width: 300px;
				height: 200px;
				margin: 0 auto;
				border: 2px dashed rgba(255, 255, 255, 0.3);
				border-radius: 10px;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				cursor: pointer;
				transition: all 0.3s ease;
				position: relative;
				background: rgba(255, 255, 255, 0.05);
			}

			.drop-zone:hover {
				border-color: #f79c42;
				background: rgba(255, 255, 255, 0.1);
			}

			.drop-zone.drag-over {
				border-color: #ff6ec7;
				background: rgba(255, 255, 255, 0.15);
				transform: scale(1.02);
			}

			.drop-zone-text {
				font-size: 16px;
				margin-bottom: 10px;
			}

			.drop-zone-subtext {
				font-size: 14px;
				color: rgba(255, 255, 255, 0.7);
			}

			/* 隐藏原始文件输入框 */
			.upload-form input[type="file"] {
				display: none;
			}

			/* 修改下载遮罩层，添加 active 类控制显示 */
			.download-overlay {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background: rgba(0, 0, 0, 0.5);
				display: flex;
				justify-content: center;
				align-items: center;
				opacity: 0;
				transition: opacity 0.3s ease;
				pointer-events: none;
				visibility: hidden;
			}

			.download-overlay.active {
				visibility: visible;
			}

			/* 修改下载按钮样式 */
			.download-btn {
				position: relative;
				background: #f79c42;
				color: white;
				padding: 12px 25px;
				border-radius: 8px;
				border: none;
				cursor: pointer;
				font-size: 16px;
				transform: translateY(10px);
				transition: all 0.3s ease;
				opacity: 0;
			}

			/* 鼠标悬停效果 */
			.image-wrapper:hover .download-overlay {
				opacity: 1;
				pointer-events: auto;
			}

			.image-wrapper:hover .download-btn {
				transform: translateY(0);
				opacity: 1;
			}

			.download-btn:hover {
				background: #ff6ec7;
				transform: translateY(-2px);
				box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
			}

			/* 修改图片结果容器样式 */
			.image-result {
				position: relative;
				width: 300px;
				margin: 0 20px;
			}

			/* 修改标题位置 */
			.image-result h3 {
				text-align: center;
				margin-bottom: 10px;
			}

			/* 结果图片容器 */
			.image-result-container {
				margin-top: 40px;
				display: none;
				justify-content: center;
				align-items: flex-start;
				gap: 40px; /* 添加间距 */
			}

			/* 图片结果区域 */
			.image-result {
				position: relative;
				width: 300px;
			}

			/* 图片包装器 */
			.image-wrapper {
				width: 300px;
				height: 300px;
				position: relative;
				border: 1px solid rgba(255, 255, 255, 0.2);
				border-radius: 10px;
				overflow: hidden;
				background: rgba(0, 0, 0, 0.1);
			}

			.image-wrapper img {
				width: 100%;
				height: 100%;
				object-fit: contain;
			}

			/* Loading 容器 */
			.loading-container {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				display: flex;
				justify-content: center;
				align-items: center;
				background: rgba(0, 0, 0, 0.1);
			}

			/* Loading 动画 */
			.loading {
				display: none;
				width: 50px;
				height: 50px;
				border: 5px solid #f3f3f3;
				border-top: 5px solid #f79c42;
				border-radius: 50%;
				animation: spin 1s linear infinite;
			}

			@keyframes spin {
				0% {
					transform: rotate(0deg);
				}
				100% {
					transform: rotate(360deg);
				}
			}

			/* 下载按钮遮罩层 */
			.download-overlay {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background: rgba(0, 0, 0, 0.5);
				display: flex;
				justify-content: center;
				align-items: center;
				opacity: 0;
				transition: opacity 0.3s ease;
				pointer-events: none;
				visibility: hidden;
			}

			.download-overlay.active {
				visibility: visible;
			}

			.image-wrapper:hover .download-overlay.active {
				opacity: 1;
				pointer-events: auto;
			}

			/* 下载按钮 */
			.download-btn {
				position: relative;
				background: #f79c42;
				color: white;
				padding: 12px 25px;
				border-radius: 8px;
				border: none;
				cursor: pointer;
				font-size: 16px;
				transform: translateY(10px);
				transition: all 0.3s ease;
				opacity: 0;
			}

			.image-wrapper:hover .download-btn {
				transform: translateY(0);
				opacity: 1;
			}

			.download-btn:hover {
				background: #ff6ec7;
				transform: translateY(-2px);
				box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
			}

			/* 标题样式 */
			.image-result h3 {
				text-align: center;
				margin-bottom: 15px;
				font-size: 18px;
				color: rgba(255, 255, 255, 0.9);
			}
		</style>
	</head>
	<body>
		<div class="container">
			<h1>除去图像背景</h1>
			<form class="upload-form" id="uploadForm" enctype="multipart/form-data">
				<div class="drop-zone" id="dropZone">
					<div class="drop-zone-text">点击或拖拽图片到这里</div>
					<div class="drop-zone-subtext">支持 jpg、png 格式</div>
				</div>
				<input
					type="file"
					name="image"
					accept="image/*"
					required
					id="fileInput"
				/>
			</form>

			<div class="image-result-container" id="imageResult">
				<div class="image-result" id="originalImage">
					<h3>原图</h3>
					<div class="image-wrapper">
						<img id="originalImageElement" src="" alt="原图" />
					</div>
				</div>
				<div class="image-result" id="processedImage">
					<h3>处理后的图像</h3>
					<div class="image-wrapper">
						<div class="loading-container">
							<div class="loading" id="loadingSpinner"></div>
						</div>
						<img
							id="resultImage"
							src=""
							alt="处理后的图像"
							style="display: none"
						/>
						<div class="download-overlay" id="downloadOverlay">
							<button class="download-btn" id="downloadBtn">下载图片</button>
						</div>
					</div>
				</div>
			</div>
		</div>

		<script>
			function resizeImageIfNeeded(image, maxSize = 2048) {
				const canvas = document.createElement("canvas");
				const ctx = canvas.getContext("2d");
				const width = image.width;
				const height = image.height;

				// 计算长边
				const maxSide = Math.max(width, height);
				if (maxSide > maxSize) {
					const scale = maxSize / maxSide;
					const newWidth = width * scale;
					const newHeight = height * scale;
					canvas.width = newWidth;
					canvas.height = newHeight;
					ctx.drawImage(image, 0, 0, newWidth, newHeight);
				} else {
					canvas.width = width;
					canvas.height = height;
					ctx.drawImage(image, 0, 0, width, height);
				}

				return canvas.toDataURL(); // 返回处理后的图像数据URL
			}

			document
				.getElementById("uploadForm")
				.addEventListener("submit", function (e) {
					e.preventDefault();

					const formData = new FormData();
					const fileInput = document.querySelector('input[type="file"]');
					const file = fileInput.files[0];

					// 读取上传的图像
					const reader = new FileReader();
					reader.onload = function (event) {
						const img = new Image();
						img.onload = function () {
							const resizedImageData = resizeImageIfNeeded(img, 2048);
							const resizedBlob = dataURLToBlob(resizedImageData);
							formData.append("image", resizedBlob, "resized_image.png");

							// 禁用提交按钮
							const submitButton = document.getElementById("submitButton");
							submitButton.disabled = true;

							// 显示图像结果容器和原图
							const imageResult = document.getElementById("imageResult");
							imageResult.style.display = "flex";
							const originalImage = document.getElementById(
								"originalImageElement"
							);
							originalImage.src = resizedImageData;

							// 显示 loading 动画
							const loadingSpinner = document.getElementById("loadingSpinner");
							loadingSpinner.style.display = "block";
							const resultImage = document.getElementById("resultImage");
							resultImage.style.display = "none";

							// 发送请求
							fetch("/remove-background", {
								method: "POST",
								body: formData,
							})
								.then((response) => response.blob())
								.then((blob) => {
									// 隐藏 loading，显示结果图
									loadingSpinner.style.display = "none";
									resultImage.style.display = "block";
									resultImage.src = URL.createObjectURL(blob);

									// 启用提交按钮
									submitButton.disabled = false;

									// 设置下载按钮
									const downloadBtn = document.getElementById("downloadBtn");
									downloadBtn.onclick = function () {
										const link = document.createElement("a");
										link.href = URL.createObjectURL(blob);
										link.download = "no_bg_image.png";
										link.click();
									};
								})
								.catch((error) => {
									console.error("Error:", error);
									loadingSpinner.style.display = "none";
									alert("处理失败，请重试。");
									submitButton.disabled = false;
								});
						};
						img.src = event.target.result;
					};
					reader.readAsDataURL(file);
				});

			function dataURLToBlob(dataURL) {
				const byteString = atob(dataURL.split(",")[1]);
				const arrayBuffer = new ArrayBuffer(byteString.length);
				const uintArray = new Uint8Array(arrayBuffer);
				for (let i = 0; i < byteString.length; i++) {
					uintArray[i] = byteString.charCodeAt(i);
				}
				return new Blob([uintArray], { type: "image/png" });
			}

			// 添加拖拽相关代码
			const dropZone = document.getElementById("dropZone");
			const fileInput = document.getElementById("fileInput");
			const downloadOverlay = document.getElementById("downloadOverlay");

			// 点击上传区域触发文件选择
			dropZone.addEventListener("click", () => {
				fileInput.click();
			});

			// 处理拖拽事件
			["dragenter", "dragover", "dragleave", "drop"].forEach((eventName) => {
				dropZone.addEventListener(eventName, preventDefaults, false);
			});

			function preventDefaults(e) {
				e.preventDefault();
				e.stopPropagation();
			}

			// 添加拖拽视觉反馈
			["dragenter", "dragover"].forEach((eventName) => {
				dropZone.addEventListener(eventName, () => {
					dropZone.classList.add("drag-over");
				});
			});

			["dragleave", "drop"].forEach((eventName) => {
				dropZone.addEventListener(eventName, () => {
					dropZone.classList.remove("drag-over");
				});
			});

			// 处理文件拖放
			dropZone.addEventListener("drop", (e) => {
				const files = e.dataTransfer.files;
				if (files.length) {
					fileInput.files = files;
					handleFile(files[0]);
				}
			});

			// 处理文件选择
			fileInput.addEventListener("change", (e) => {
				if (e.target.files.length) {
					handleFile(e.target.files[0]);
				}
			});

			// 修改原有的表单提交代码
			function handleFile(file) {
				const reader = new FileReader();
				reader.onload = function (event) {
					const img = new Image();
					img.onload = function () {
						const resizedImageData = resizeImageIfNeeded(img, 2048);
						const resizedBlob = dataURLToBlob(resizedImageData);
						uploadImage(resizedBlob);
					};
					img.src = event.target.result;
				};
				reader.readAsDataURL(file);
			}

			function uploadImage(blob) {
				const formData = new FormData();
				formData.append("image", blob, "resized_image.png");

				// 禁用拖拽区域
				dropZone.style.pointerEvents = "none";
				dropZone.style.opacity = "0.6";

				// 显示图像结果容器和原图
				const imageResult = document.getElementById("imageResult");
				imageResult.style.display = "flex";

				// 设置原图
				const originalImage = document.getElementById("originalImageElement");
				originalImage.src = URL.createObjectURL(blob);

				// 显示 loading
				const loadingSpinner = document.getElementById("loadingSpinner");
				loadingSpinner.style.display = "block";
				const resultImage = document.getElementById("resultImage");
				resultImage.style.display = "none";

				// 确保下载遮罩层处于隐藏状态
				downloadOverlay.classList.remove("active");

				fetch("/remove-background", {
					method: "POST",
					body: formData,
				})
					.then((response) => response.blob())
					.then((blob) => {
						loadingSpinner.style.display = "none";
						resultImage.style.display = "block";
						resultImage.src = URL.createObjectURL(blob);

						// 启用下载功能
						downloadOverlay.classList.add("active");
						const downloadBtn = document.getElementById("downloadBtn");
						downloadBtn.onclick = () => {
							const link = document.createElement("a");
							link.href = URL.createObjectURL(blob);
							link.download = "no_bg_image.png";
							link.click();
						};

						// 重新启用拖拽区域
						dropZone.style.pointerEvents = "auto";
						dropZone.style.opacity = "1";
					})
					.catch((error) => {
						console.error("Error:", error);
						loadingSpinner.style.display = "none";
						alert("处理失败，请重试。");
						dropZone.style.pointerEvents = "auto";
						dropZone.style.opacity = "1";
					});
			}
		</script>
	</body>
</html>
